//
//  PublishThingsViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/7/23.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "PublishThingsViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "Config.h"
#import "UIImage+fixOrientation.h"
#import "Utils.h"
#import "ZYQAssetPickerController.h"
#import "Helper.h"
#import "Tweet.h"
#import "MWPhotoBrowser.h"
#import "UIColor+Addition.h"

#import "UIViewExt.h"
#import "HGPhotoWall.h"
#import "MWPhotoBrowser.h"
#import "QBImagePickerController.h"
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define imgViewTag 300
#define closeBtnTag 500

@interface PublishThingsViewController ()< UINavigationControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIScrollViewDelegate,QBImagePickerControllerDelegate,MWPhotoBrowserDelegate,HGPhotoWallDelegate,UITextViewDelegate>{
    
    UITextField *titleField;
    UITextView *contentView;
    UIButton *addPicBtn;
    NSInteger lastArrayCount;
    NSMutableArray *imgDataArray,*photos;
    NSArray *picArray;
    NSString *picsUrlString,*urlString;
    MBProgressHUD *picHud;
    UIScrollView *writeScrollView;
    UIView *picsView;
}

@property (nonatomic, strong) HGPhotoWall *photoWall;
@property (strong, nonatomic) Tweet *curTweet;

@end

@implementation PublishThingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"村里事发布";
    [self.view setBackgroundColor:[UIColor colorWithHexString:UIBgColorValue]];
    _curTweet = [Tweet tweetForSend];//存放已选图片url
    imgDataArray=[[NSMutableArray alloc]init];//存放选中图片
    photos = [NSMutableArray array];//存放浏览的大图
    
    [self createNavBtn];
    [self createWriteView];
    [self addTapRecoginzer];
}

-(void)createNavBtn{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(publishThings) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
}

#pragma mark - 发布内容

-(void)publishThings{
    
    if ([titleField.text isEqualToString:@""]||[contentView.text isEqualToString:@""]) {
        [self showAlertWithMessage:@"标题或内容不能为空!"];
    }else{
        
        if (imgDataArray.count<1) {
            [self sendContent];
        }else{
            [self uploadPics];
        }
    }
}

-(void)sendContent{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:titleField.text forKey:@"title"];
    [CheckParams setObject:contentView.text forKey:@"content"];
    
    if (picsUrlString) {
        [CheckParams setObject:picsUrlString forKey:@"pics"];
    }else{
        [CheckParams setObject:@"http://1.jpg" forKey:@"pics"];
    }
    
    urlString=@"publish_sbnews.php";
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:urlString httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSLog(@"%@",result);
        [picHud hide:YES];
        NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
        if (str) {
            
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
            hud.labelText = @"发送失败!";
            [hud hide:YES afterDelay:1];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            MBProgressHUD *hud = [Config createHUD];
            hud.mode = MBProgressHUDModeCustomView;
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"发送成功!";
            [hud hide:YES afterDelay:1];
            [self.navigationController popViewControllerAnimated:YES];
            self.curTweet.selectedAssetURLs=nil;
        }
    }failureAction:^{
        
    }];
    
}

-(void)uploadPics{
    
    picHud= [Config createHUD];
    picHud.mode = 0;
    picHud.labelText = @"上传图片中...";
    picHud.userInteractionEnabled=NO;
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    NSMutableDictionary *file=[[NSMutableDictionary alloc]init];
    [file setValue:imgDataArray forKey:@"image[]"];
    [MyDataService requestURL:@"upfile_imgs.php" httpMethod:@"POST" params:CheckParams fileDatas:file complection:^(id result) {
        
        [picHud hide:YES];
        NSData *data=result;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@", dic);
        NSDictionary *dataDic=[dic objectForKey:@"date"];
        picArray=[[NSArray alloc]initWithArray:[dataDic objectForKey:@"pics"]];
        
        if (!picArray.count==imgDataArray.count) {
            
            [self showAlertWithMessage:@"上传图片失败!"];
            return ;
        }
        
        for (int i=0; i<picArray.count; i++) {
            
            if (i==0) {
                NSString *picUrlString=[NSString stringWithFormat:@"%@",[picArray objectAtIndex:i]];
                picsUrlString=picUrlString;
            }else{
                NSString *picUrlString=[NSString stringWithFormat:@",%@",[picArray objectAtIndex:i]];
                picsUrlString=[NSString stringWithFormat:@"%@%@",picsUrlString,picUrlString];
            }
        }
        NSLog(@">>>>>>>>>>>>%@",picsUrlString);
        [self sendContent];
    }failureAction:^{
        
        [picHud hide:YES];
        [self showAlertWithMessage:@"上传图片失败!"];
    }];
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)goBack{
    
    [picHud removeFromSuperview];
    self.curTweet.selectedAssetURLs=nil;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)createWriteView{
    
    writeScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight)];
    writeScrollView.contentSize= CGSizeMake(kScreenWidth, kScreenHeight);
    writeScrollView.delegate=self;
    [self.view addSubview:writeScrollView];
    
    UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 10, 40, 25)];
    titleLabel.text=@"标题";
    titleLabel.textAlignment=0;
    [writeScrollView addSubview:titleLabel];
    
    titleField=[[UITextField alloc]initWithFrame:CGRectMake(15, 40, kScreenWidth-30, 30)];
    titleField.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    titleField.layer.borderWidth =0.5;
    titleField.layer.cornerRadius=2.0;
    titleField.backgroundColor=[UIColor whiteColor];
    [writeScrollView addSubview:titleField];
    
    UILabel *contentLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 75, 40, 25)];
    contentLabel.text=@"内容";
    contentLabel.textAlignment=0;
    [writeScrollView addSubview:contentLabel];
    
    contentView=[[UITextView alloc]initWithFrame:CGRectMake(15, 105, kScreenWidth-30, 120)];
    contentView.font=[UIFont systemFontOfSize:17];
    contentView.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    contentView.layer.borderWidth =0.5;
    contentView.layer.cornerRadius = 2.0;
    contentView.delegate=self;
    [writeScrollView addSubview:contentView];
    
    UILabel *remindLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 233, 120, 20)];
    remindLabel.text=@"仅限两张图片";
    remindLabel.textAlignment=0;
    [writeScrollView addSubview:remindLabel];
    
    picsView = [[UIView alloc] initWithFrame:CGRectMake(12, 255, kScreenWidth-20, 70)];
    [writeScrollView addSubview:picsView];
    self.photoWall = [[HGPhotoWall alloc] initWithFrame:CGRectMake(0, 0, 0, 0) andLayoutPhotoType:LayoutTwelfPhotos];
    [self.photoWall setPhotos:nil];
    self.photoWall.delegate = self;
    [self.photoWall setEditModel:YES];
    [picsView addSubview:_photoWall];
}

#pragma mark -actionSheet代理方法

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        //拍照
        [self takePhoto];
    }else if (buttonIndex == 1) {
        //从相册中选择
        [self openLocalPhoto];
    }
}

#pragma mark - 拍照
- (void)takePhoto{
    
    if (imgDataArray.count>2) {
        [self showAlertWithMessage:@"最多选择2张图片!"];
        return;
    }
    
    if (![Helper checkCameraAuthorizationStatus]) {
        return;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;//设置可编辑
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
}

#pragma mark - 打开本地相册
-(void)openLocalPhoto{
    
    if (![Helper checkPhotoLibraryAuthorizationStatus]) {
        return;
    }
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    [imagePickerController.selectedAssetURLs removeAllObjects];
    [imagePickerController.selectedAssetURLs addObjectsFromArray:self.curTweet.selectedAssetURLs];
    imagePickerController.filterType = QBImagePickerControllerFilterTypePhotos;
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 2;
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [self presentViewController:navigationController animated:YES completion:NULL];
}

#pragma mark -QBImagePickerControllerDelegate代理方法

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{
    
    NSMutableArray *selectedAssetURLs = [NSMutableArray new];
    [imagePickerController.selectedAssetURLs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [selectedAssetURLs addObject:obj];
    }];
    
    self.curTweet.selectedAssetURLs = selectedAssetURLs;
    
    //移除上次数据
    [photos removeAllObjects];
    [imgDataArray removeAllObjects];
    
    [_photoWall removeFromSuperview];
    self.photoWall = [[HGPhotoWall alloc] initWithFrame:CGRectMake(0, 0, 0, 0) andLayoutPhotoType:LayoutTwelfPhotos];
    self.photoWall.backgroundColor = [UIColor whiteColor];
    [self.photoWall setPhotos:nil];
    self.photoWall.delegate = self;
    [self.photoWall setEditModel:YES];
    [picsView addSubview:_photoWall];
    
    for (int i=0; i<assets.count; i++) {
        
        ALAsset *asset=assets[i];
        UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        
        if (tempImg.size.width>1024 && tempImg.size.height>1024) {
            tempImg = [Utils sizeCompressImageTo1024With:tempImg];
        }
        
        NSData *data=UIImageJPEGRepresentation(tempImg,0.4);
        //判断图片大小确定压缩比例
        if (data.length>1024*1024) {
            data=UIImageJPEGRepresentation(tempImg,0.2);
        }
        [imgDataArray addObject:data];
        
        MWPhoto *photo = [MWPhoto photoWithImage:tempImg];
        [photos addObject:photo];
        [self.photoWall addLocalPhoto:tempImg];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark UIImagePickerControllerDelegate完成拍照

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *pickerImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
    
    [assetsLibrary writeImageToSavedPhotosAlbum:[pickerImage CGImage] orientation:(ALAssetOrientation)pickerImage.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error) {
        
        [self.curTweet addASelectedAssetURL:assetURL];
        
        UIImage *tempImgOrientation = [pickerImage fixOrientation];
        
        if (tempImgOrientation.size.width>1024 && tempImgOrientation.size.height>1024) {
            tempImgOrientation = [Utils sizeCompressImageTo1024With:tempImgOrientation];
        }
        [self.photoWall addLocalPhoto:tempImgOrientation];
        MWPhoto *photo = [MWPhoto photoWithImage:tempImgOrientation];
        [photos addObject:photo];
        
        NSData *data=UIImageJPEGRepresentation(tempImgOrientation,0.4);
        //判断图片大小确定压缩比例
        if (data.length>1024*1024) {
            data=UIImageJPEGRepresentation(tempImgOrientation,0.2);
        }
        [imgDataArray addObject:data];
        
    }];
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击屏幕事件

- (void)addTapRecoginzer
{
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignTheKeyboard)];
    [self.view addGestureRecognizer:tap];
}

- (void)resignTheKeyboard
{
    [self.view endEditing:YES];
    if (writeScrollView.frame.origin.y!=0) {
        writeScrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma - mark HGPhoto Delegate

- (void)photoWallPhotoTaped:(NSUInteger)index{
    
    [imgDataArray removeObjectAtIndex:index];
    [self.photoWall deletePhotoByIndex:index];
    [photos removeObjectAtIndex:index];
    [self.curTweet.selectedAssetURLs removeObjectAtIndex:index];
}

- (void)photoWallAddAction{
    
    [self resignTheKeyboard];
    if (imgDataArray.count>1) {
        [self showAlertWithMessage:@"最多选择2张图片!"];
        return;
    }
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择", nil];
    sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [sheet showInView:self.view];
}

#pragma mark 浏览大图

- (void)photoWallPhotoBrowser:(NSUInteger)index{
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.isScrollerPic=YES;
    [browser setCurrentPhotoIndex:index];
    [self.navigationController pushViewController:browser animated:YES];
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < photos.count) {
        return [photos objectAtIndex:index];
    }
    return nil;
}

#pragma mark - textView将要开始编辑

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if (kScreenWidth==320) {
        
        writeScrollView.frame = CGRectMake(0, -70, kScreenWidth, kScreenHeight);
    }
    return YES;
}

@end
